//用户管理
var basicUserPositionIdField = {
    "name": "positionId.id",
    displayField: 'positionName',
    valueField: 'id',
    text: '所属岗位',
    req: true,
    xtype: 'jselectgrid',
    grid: {
        order: ['positionType->asc'],
        where: [['organId.id', '=', USER.areaId]],
        top: [{
            xtype: 'combo',
            text: '岗位类型',
            op: '=',
            store: $.dic('stationType'),
            name: 'positionType'
        }, {
            xtype: 'textfield',
            text: '岗位名称',
            op: 'like',
            name: 'positionName'
        }, $.search],
        clazz: BasicPosition,
        columns: [{
            width: 200,
            "name": "positionType",
            renderer: $.dicRenderer('stationType')
        }, {
            width: 200,
            "name": "positionName"
        }, {
            flex: 1,
            "name": "positionReson"
        }]
    }
}

function user_main() {
    return $.layout({
        id: 'user-main-app',
        items: [{
            startId: USER.areaId,
            startSelf: true,
            mapper: 'id,organName,organParentId.id,organType',
            id: 'BasicUse_BasicOrganization_main',
            xtype: 'jtree',
            style: $.border('Right'),
            clazz: BasicOrganization,
            order: ['organSort->asc'],
            width: 220,
            region: 'west',
            change: [{
                target: 'BasicUser_main',
                targetField: 'organId.id'
            }]
        }, {
            autoLoad: false,
            viewCls: 'user-main',
            region: 'center',
            shir: 'basicUserShir.userOrgTreeShir',
            id: 'BasicUser_main',
            xtype: 'jview',
            clazz: BasicUser,
            order: ['state->desc'],
            top: [{
                xtype: 'textfield',
                op: 'like',
                name: 'name'
            }, {
                xtype: 'textfield',
                op: 'like',
                name: 'phone'
            }, $.search, '|', {
                key: 'A',
                id: 'adduser',
                iconCls: ion.add,
                text: '添加用户',
                handler: function () {
                    var row = $('BasicUse_BasicOrganization_main')
                        .select()[0];
                    BasicUser_form().save({
                        msg: '用户已成功添加',
                        shir: 'basicUserShir.userSaveShri',
                        text: '开通账户',
                        rk: {
                            id: 'BasicUse_BasicOrganization_main',
                            msg: '选中一个组织机构后进行添加',
                            exp: ['id->organId.id']
                        },
                        grid: ['BasicUser_main']
                    });
                }
            }, {
                id: 'editUser',
                key: 'E',
                iconCls: ion.edit,
                text: '修改用户',
                handler: function () {
                    BasicUser_form().edit({
                        msg: '用户修改成功!',
                        grid: ['BasicUser_main']
                    });
                }
            }, {
                id: 'delUser',
                key: 'D',
                iconCls: ion.del,
                text: '删除用户',
                handler: function () {
                    $('BasicUser_main').deletes({
                        validate: [
                            [BasicLog, 'opUser',
                                '该人员存在日志数据无法删除.'],
                            [BasicPartTime, 'userId.id',
                                '该人员存兼职信息无法删除.'],
                            [BasicRoleUser, 'userId.id',
                                '该人员存在相关角色信息无法删除.'],
                            [BasicPortal, 'userId.id',
                                '该人员存在相关快捷方式信息无法删除.']]
                    });
                }
            }, {
                text: '查看用户',
                iconCls: 'fa-search',
                id: 'viewUser',
                handler: function () {
                    BasicUser_form().view({
                        grid: 'BasicUser_main'
                        // entityId : r.get('id')
                    });
                }
            }, '|', {
                id: 'updateUserState',
                key: 'F',
                iconCls: 'fa-pencil',
                text: '修改用户状态',
                handler: function () {
                    var grid = $('BasicUser_main');
                    var sel = grid.select()[0];
                    if (!sel) {
                        return $.error('请选中需要修改状态的用户!');
                    }
                    var cmd = function (state) {
                        var oldState = sel.get('state');
                        if (oldState == state) {
                            return $.error('状态没有发生改变无需修改。')
                        }
                        $.cmd({
                            clazz: BasicUser,
                            type: 'save',
                            params: {
                                id: sel.get('id'),
                                state: state
                            },
                            callback: function () {
                                grid.reset();
                                $.show('状态修改成功!');
                                win.close();
                            }
                        });
                    }
                    var win = $({
                        modal: true,
                        title: '修改用户状态',
                        xtype: 'window',
                        bodyPadding: 40,
                        html: Ext.String.format(
                            '您正在修改账户为【{0}】的状态.', sel
                                .get('uname')),
                        buttons: [{
                            cls: 'green',
                            text: '启用',
                            handler: function () {
                                cmd('1');
                                $.cancel.handler();
                            }
                        }, {
                            cls: 'red',
                            text: '停封',
                            handler: function () {
                                cmd('0');
                            }
                        }, $.cancel],
                        width: 350
                    }).show();
                }

            },
                /*{
                id : 'userJZ',
                iconCls : 'fa-slideshare',
                text : '兼职',
                cls : 'violet',
                handler : function() {
                    var sel = $('BasicUser_main').select()[0];
                    if (!sel) {
                        return $.error('请选中需要兼职的人员!')
                    }
                    $.cmd({
                        type : 'select',
                        clazz : BasicPartTime,
                        where : [['userId.id', '=',
                                sel.get('id')]],
                        fields : ['positionId.id',
                                'organId.id',
                                'positionId.stationName',
                                'organId.organName'],
                        callback : function(result) {
                            // 初始化
                            var initData = [], treeIds = [];
                            $.each(result.data, function(row) {
                                treeIds.push(row['organId.id']);
                                initData.push({
                                    oname : row['organId.organName'],
                                    pname : row['positionId.stationName'],
                                    oid : row['organId.id'],
                                    pid : row['positionId.id']
                                })
                            });

                            var form = $({
                                width : 700,
                                xtype : 'jform',
                                hides : [{
                                            name : 'uid',
                                            value : sel
                                                    .get('id')
                                        }],
                                fields : [{
                                            size : 1 / 3,
                                            text : '人员姓名',
                                            readOnly : true,
                                            value : sel
                                                    .get('name')
                                        }, {
                                            size : 1 / 3,
                                            text : '主要部门',
                                            readOnly : true,
                                            value : sel
                                                    .get('organ.organName')
                                        }, {
                                            size : 1 / 3,
                                            text : '主要岗位',
                                            readOnly : true,
                                            value : sel
                                                    .get('positionId.stationName')
                                        }, {
                                            size : 0.5,
                                            iconCls : 'fa-arrow-circle-o-right',
                                            xtype : 'jtree',
                                            title : '可兼职组织机构',
                                            mapper : 'id,organName,organParentId.id,organType,iconCls,cls',
                                            id : 'BasicPartTime_tree',
                                            where : [[
                                                    'id',
                                                    '!=',
                                                    sel
                                                            .get('organ.id')]],
                                            startId : USER.areaId,
                                            top : [$.treeSearch],
                                            xtype : 'jtree',
                                            height : 300,
                                            ckModel : 'all',
                                            clazz : BasicOrganization,
                                            loadFn : function(
                                                    cmp) {
                                                cmp
                                                        .setCheckedNodes(treeIds);
                                            },
                                            listeners : {
                                                checkchange : function(
                                                        node,
                                                        chekced) {
                                                    var grid = $('part_time_grid');
                                                    if (chekced) {
                                                        grid
                                                                .insertRow(
                                                                        {
                                                                            oid : node
                                                                                    .get('id'),
                                                                            oname : node
                                                                                    .get('text')
                                                                        },
                                                                        grid.plugins[0],
                                                                        1);
                                                    } else {
                                                        grid
                                                                .getStore()
                                                                .remove(grid
                                                                        .getStore()
                                                                        .findRecord(
                                                                                'oid',
                                                                                node
                                                                                        .get('id')))
                                                    }
                                                }
                                            },
                                            order : ['organSort->asc']
                                        }, {
                                            id : 'part_time_grid',
                                            iconCls : "fa-arrow-circle-o-left",
                                            page : false,
                                            size : 0.5,
                                            height : 300,
                                            xtype : 'jgrid',
                                            hides : ['oid',
                                                    'pid'],
                                            plugins : [Ext
                                                    .create(
                                                            'Ext.grid.plugin.CellEditing',
                                                            {})],
                                            columns : [{
                                                        width : 150,
                                                        name : 'oname',
                                                        text : '兼职机构'
                                                    }, {
                                                        flex : 1,
                                                        name : 'pname',
                                                        text : '兼职岗位',
                                                        editor : {
                                                            displayField : 'stationName',
                                                            valueField : 'stationName',
                                                            xtype : 'combo',
                                                            listeners : {
                                                                change : function(
                                                                        cmp,
                                                                        v) {
                                                                    var id = cmp
                                                                            .getStore()
                                                                            .findRecord(
                                                                                    'stationName',
                                                                                    v)
                                                                            .get('id');
                                                                    var grid = $('part_time_grid');
                                                                    grid
                                                                            .select()[0]
                                                                            .set(
                                                                                    'pid',
                                                                                    id);
                                                                }
                                                            },
                                                            store : $
                                                                    .store(
                                                                            {
                                                                                autoLoad : true,
                                                                                clazz : BasicPosition,
                                                                                rule : [[
                                                                                        'oid.id',
                                                                                        '=',
                                                                                        'areaId']],
                                                                                fields : [
                                                                                        'id',
                                                                                        'stationName']
                                                                            })

                                                        }
                                                    }],
                                            store : Ext
                                                    .create(
                                                            'Ext.data.Store',
                                                            {
                                                                fields : [
                                                                        'oname',
                                                                        'oid',
                                                                        'pname',
                                                                        'pid'],
                                                                data : initData
                                                            }),
                                            title : '兼职详情'

                                        }]
                            });
                            form.win({
                                title : '人员兼职',
                                buttons : [{
                                    text : '保存兼职设置',
                                    handler : function() {
                                        var form = this
                                                .up('window')
                                                .down('jform');
                                        var data = $('BasicPartTime_tree')
                                                .getCheckedIds();
                                        var grid = $('part_time_grid');
                                        grid
                                                .getStore()
                                                .commitChanges();
                                        var oids = [], pids = [], success = true;
                                        grid.getStore().each(
                                                function(row) {
                                                    var pid = row
                                                            .get('pid');
                                                    if (pid == null
                                                            || pid == '') {
                                                        $
                                                                .error('兼职机构【'
                                                                        + row
                                                                                .get('oname')
                                                                        + "】没有设置岗位!")
                                                        return success = false;
                                                    }
                                                    pids
                                                            .push(pid);
                                                    oids
                                                            .push(row
                                                                    .get('oid'));
                                                });
                                        if (success) {
                                            $.orm.mtm({
                                                clazz : BasicPartTime,
                                                src : 'userId',
                                                srcId : form
                                                        .get('uid')
                                                        .v(),
                                                infos : [{
                                                    tagerField : 'organId',
                                                    ids : oids
                                                            .join(',')
                                                }, {
                                                    tagerField : 'positionId',
                                                    ids : pids
                                                            .join(',')
                                                }],
                                                callback : function() {
                                                    $
                                                            .show('兼职设置成功.')
                                                    form.win
                                                            .close();
                                                }
                                            })
                                        }
                                    }
                                }]
                            })
                        }
                    })
                }
            },*/ {
                    id: 'roleFP',
                    iconCls: 'fa-flask',
                    text: '分配角色',
                    handler: function () {
                        BasicUser_main_distribution_role();
                    },
                    cls: 'black'
                }, {
                    id: 'resetUserPwd',
                    iconCls: 'fa-bars',
                    text: '重置密码',
                    cls: 'blue',
                    handler: function () {
                        $('BasicUser_main').rowRequest({
                            url: 'admin/resetPwd',
                            msg: '确定重置该用户密码吗？重置后密码同一为888888.',
                            callback: function (text) {
                                if (text) {
                                    $.show('密码重置成功!');
                                }
                            }
                        })
                    }
                }],
            itemSelector: 'div.list-view-a',
            pageSize: 10,
            fields: ['positionId.positionName', 'organId.organName'],
            tpl: Ext
                .create(
                    'Ext.XTemplate',
                    '<tpl for=".">',
                    '<div class="list-view-a">',
                    '<div class="list-view-img"><img src="{[values.userImg]}" /><br/><span class="list-view-left">{[values["positionId.positionName"]]}</span><br/><br/><span class="{[this.getCls(values.state)]}">{[DICS.userState[values.state]]}</span></div>',
                    '<div class="list-view-right"><h3 style="color:#35BAF6;font-weight: 600;height:0px">{name}</h3>',
                    '<br/><i class="fa-phone-square fa x-fa-logo"></i> 手机：<span class="list-view-txt">{phone}</span> ',
                    '<br/><i class="fa-envelope-square fa x-fa-logo"></i> 邮箱：<span class="list-view-txt">{emali}</span>',
                    '<br/><i class="fa-qq fa x-fa-logo"></i> QQ：<span class="list-view-txt">{qq}</span>',
                    '<br/><br/>&nbsp;&nbsp;&nbsp<a href="javascript:void(1)" >{[values["organId.organName"]]}</a>',
                    '</div></div></tpl>', {
                        getCls: function (state) {
                            return state == '1'
                                ? 'x-fa-label-green'
                                : (state == '0'
                                    ? 'x-fa-label-red'
                                    : 'x-fa-label-ogn');
                        }
                    })
        }]

    })
}

function BasicUser_form() {
    return $({
        xtype: 'jform',
        clazz: BasicUser,
        printAction: 'user',
        fieldsSize: 0.5,
        hides: [{
            name: 'state',
            value: '1'
        }, {
            name: 'areaId.id',
            value: USER.areaId
        }],
        validate: [['phone = ?', 'phone', '该手机号已经注册'],
            ['idcard = ?', 'idcard', '该身份证已经注册']],
        fields: [{
            req: true,
            name: 'userImg',
            xtype: 'imgfield'
        }, {
            text: '组织机构',
            req: true,
            "name": "organId.id",
            xtype: 'jselecttree',
            tree: {
                startId: USER.areaId,
                clazz: BasicOrganization,
                mapper: 'id,organName,organParentId.id'
            }
        }, basicUserPositionIdField, {
            name: 'workNo',
            req: true
        }, {
            name: 'name',
            req: true
        }, {
            req: true,
            maxLength: 11,
            minLength: 11,
            "name": "phone"
        }, {
            maxLength: 18,
            minLength: 18,
            vtype: 'id_card',
            "name": "idcard"
        }, {
            req: true,
            vtype: 'email',
            "name": "email"
        }, {
            "name": "qq",
            vtype: 'qq'
        }, {
            size: 1,
            xtype: 'displayfield',
            value: $.color('red', '【账号为手机号，初始密码为888888，创建后由用户自行修改密码】')
        }]
    })
}

// 角色分配
function BasicUser_main_distribution_role() {
    var sel = $('BasicUser_main').select()[0], selectNode = $('BasicUse_BasicOrganization_main')
        .select()[0];
    if (!selectNode) {
        return $.error('选择一个组织机构后再分配角色')
    } else if (!sel) {
        return $.error('请选中一个人员后再进行角色分配');
    }
    // 找出所属企业域
    var node = null;
    selectNode.bubble(function (n) {
        node = n;
        return !(node.get('organType') == 'area')
    });
    if (!node) {
        alert('未从当前组织机构中检测到企业域的存在!');
        return false;
    }

    var name = sel.get('name'), id = sel.get('id');
    $.orm.getMtm({
        tagerFields: ['roleId'],
        clazz: BasicRoleUser,
        src: 'userId',
        srcId: id,
        callback: function (data) {
            var form = $({
                width: 450,
                xtype: 'jform',
                fields: [{
                    text: '人员姓名',
                    value: name,
                    readOnly: true
                }, {
                    xtype: 'itemselector',
                    height: 250,
                    value: data.roleId,
                    displayField: 'roleName',
                    valueField: 'id',
                    id: 'basic_user_role_itemselector',
                    store: $.store({
                        clazz: BasicRole,
                        fields: ['roleName', 'id'],
                        where: [['roleType', '=', '1'],
                            ['organId.id', '=', node.get('id')]]
                    }),
                    text: '人员角色'
                }]
            });
            form.win({
                buttons: [{
                    text: '完成',
                    cls: 'green',
                    iconCls: 'fa-hand-o-down',
                    handler: function () {
                        $.orm.mtm({
                            clazz: BasicRoleUser,
                            src: 'userId',
                            srcId: id,
                            infos: [{
                                tagerField: 'roleId',
                                ids: $('basic_user_role_itemselector')
                                    .v().join(',')
                            }],
                            callback: function () {
                                $
                                    .show(Ext.String
                                        .format(
                                            '人员【{0}】的角色已成功分配',
                                            name));
                                form.win.close();
                            }
                        });
                    }
                }],
                title: Ext.String.format('为【{0}】分配角色', name)
            });
        }
    });

}
